#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;

using System.Web;

using System.Collections;
using WaveMaster.Holidays.Club.Domain;
using WaveMaster.Holidays.Club.Service;

#endregion

namespace WaveMaster.Holidays.Club.Web
{
    public partial class UserForm : Form
    {
        User m_user;
        User m_current_user;
        EditMode m_editmode;
        UserService m_userService;
        MainForm m_mainForm;
        TravelAgentService m_TravelAgentService;
        UserControlManageUser m_parentForm;

        public UserForm(string name, User user, User currentUser, MainForm mainForm, UserControlManageUser parentForm, EditMode editmode)
        {
            InitializeComponent();
            m_userService = (UserService)ServiceFactory.Instance().GetService(ServiceFactory.USERSERVICE);
            m_TravelAgentService = (TravelAgentService)ServiceFactory.Instance().GetService(ServiceFactory.TRAVEL_AGENT_SERVICE);
            m_current_user = currentUser;
            m_mainForm = mainForm;
            this.Name = name;
            m_parentForm = parentForm;
            initButtonEvent();
            initComboDataSource();
            setEditMode(editmode);
            if (user.UserID == 0)
            {
                clearForm();
            }
            else
            {
                m_user = m_userService.GetUserByUserID(user.UserID);
                loadUser(); 
                enableForm(editmode == EditMode.Edit);
            }
            //enableForm(false);
        }

        private void clearForm()
        {
            textBoxUserName.Text = string.Empty;
            textBoxUserCode.Text = string.Empty;
            textBoxPassword.Text = string.Empty;
            textBoxConfirmPassword.Text = string.Empty;
            textBoxEmail.Text = string.Empty;

            checkBoxBP.Checked = false;
            checkBoxWC.Checked = false;
            textBoxBPPrintername.Enabled = false;
            textBoxWCPrinterName.Enabled = false;

            textBoxBPPrintername.Text = string.Empty;
            textBoxWCPrinterName.Text = string.Empty;
            textBoxMACAddress.Text = string.Empty;

            dateTimePickerExpiry.Value = DateTime.Today.AddMonths(3);
            checkBoxPasswordExpired.Checked = true;
            comboBoxUserType.SelectedIndex = 0;
            comboBoxTravelAgent.Text = m_current_user.TravelAgent.ToString();
            checkBoxActive.Checked = true;
            //comboBoxRoleMaster.SelectedIndex = 0;
            m_user = new User();
            // listViewRecords.SelectedItems.Clear();
            clearErrorProvider();
            enableForm(true);
            setEditMode(EditMode.Create);
            //textBoxUserCode.SelectAll();
            comboBoxTravelAgent.Focus();
        }

        private void initButtonEvent()
        {
            //toolBarButtonClear.Click += new EventHandler(toolBarButtonClear_Click);
            toolBarButtonSave.Click += new EventHandler(toolBarButtonSave_Click);
            //toolBarButtonDelete.Click += new EventHandler(toolBarButtonDelete_Click);
            toolBarButtonRefresh.Click += new EventHandler(toolBarButtonRefresh_Click);
            toolBarButtonEdit.Click += new EventHandler(toolBarButtonEdit_Click);
            //toolBarButtonSearch.Click += new EventHandler(toolBarButtonSearch_Click);
            toolBarButtonCancel.Click += new EventHandler(toolBarButtonCancel_Click);

            dataGridViewRoleMasters.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridViewRoleMasters_CellValidating);
            dataGridViewRoleMasters.CellValidated += new DataGridViewCellEventHandler(dataGridViewRoleMasters_CellValidated);
            dataGridViewRoleMasters.CellClick += new DataGridViewCellEventHandler(dataGridViewRoleMasters_CellClick);
        }

        void dataGridViewRoleMasters_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dataGridViewButtonColumnRemove.Index)
            {
                if (dataGridViewRoleMasters[dataGridViewComboBoxColumnRoleMaster.Index, e.RowIndex].Value != null)
                    dataGridViewRoleMasters.Rows.RemoveAt(e.RowIndex);
            }
        }

        void dataGridViewRoleMasters_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            errorProviderUser.SetError(dataGridViewRoleMasters, "");

            foreach (DataGridViewRow v in dataGridViewRoleMasters.Rows)
            {
                dataGridViewRoleMasters.Rows[v.Index].ErrorText = "";
            }
        }

        void dataGridViewRoleMasters_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            foreach (DataGridViewRow v in dataGridViewRoleMasters.Rows)
            {
                if (e.RowIndex == v.Index) continue;
                if (dataGridViewRoleMasters[dataGridViewComboBoxColumnRoleMaster.Index, v.Index].Value == null) continue;
                string rolemaster = dataGridViewRoleMasters[dataGridViewComboBoxColumnRoleMaster.Index, v.Index].Value.ToString();
                if (rolemaster == e.FormattedValue.ToString())
                {
                    dataGridViewRoleMasters.Rows[e.RowIndex].ErrorText = rolemaster + " has been add";
                    errorProviderUser.SetError(dataGridViewRoleMasters, rolemaster + " has been add");
                    e.Cancel = true;
                }
            }
        }

        void toolBarButtonEdit_Click(object sender, EventArgs e)
        {
            setEditMode(EditMode.Edit);
            enableForm(!toolBarButtonEdit.Enabled);
        }

        void toolBarButtonCancel_Click(object sender, EventArgs e)
        {
            if (m_editmode == EditMode.Load)
                this.Close();
            else
            MessageBox.Show("Are you sure to cancel?", "Confirmation", MessageBoxButtons.YesNo,
               MessageBoxIcon.Question, new EventHandler(cancelConfirmation));
        }

        void cancelConfirmation(object sender, EventArgs e)
        {
             MessageBoxWindow msg = (MessageBoxWindow)sender;
             if (msg.DialogResult == DialogResult.Yes)
             {
                 this.Close();
             }
        }
        private void initComboDataSource()
        {
           // IList rolemasters = m_userService.LoadAllRoleMaster();
           // comboBoxRoleMaster.DataSource = rolemasters;
            dataGridViewComboBoxColumnRoleMaster.DataSource = GetDataGridRoleMasterComboValues();
            comboBoxTravelAgent.DataSource = m_TravelAgentService.LoadAllTravelAgent();
            comboBoxUserType.DataSource = Enum.GetValues(typeof(UserType));
        }

        private IList GetDataGridRoleMasterComboValues()
        {
            IList rolemasters = m_userService.LoadAllRoleMaster();
            IList cbvals = new ArrayList();
            foreach (RoleMaster m in rolemasters)
            {
                cbvals.Add(m.RoleName);
            }
            return cbvals;
        }

        private RoleMaster GetRoleMasterByName(string name)
        {
            IList rolemasters = m_userService.LoadAllRoleMaster();
            RoleMaster result = null;
            foreach (RoleMaster m in rolemasters)
            {
                if (m.RoleName == name)
                {
                    result = m;
                    break;
                }
            }
            return result;
        }

        void toolBarButtonRefresh_Click(object sender, EventArgs e)
        {
            //loadAllUser();
            initComboDataSource();
            if (m_editmode == EditMode.Load || m_editmode == EditMode.Edit)
                loadUser();
        }

        private void clearErrorProvider()
        {
            errorProviderUser.SetError(textBoxUserCode, "");
            errorProviderUser.SetError(textBoxUserName, "");
            errorProviderUser.SetError(textBoxPassword, "");
            errorProviderUser.SetError(textBoxConfirmPassword, "");
            errorProviderUser.SetError(comboBoxTravelAgent, "");
            //errorProviderUser.SetError(comboBoxRoleMaster, "");
        }
        private bool isValidForm()
        {
            clearErrorProvider();
            bool valid_a = textBoxUserCode.Text != string.Empty;
            bool valid_b = textBoxUserName.Text != string.Empty;
            bool valid_c = textBoxPassword.Text != string.Empty;
            bool valid_d = textBoxPassword.Text == textBoxConfirmPassword.Text;
            bool valid_e = comboBoxTravelAgent.SelectedItem != null;
            //bool valid_e = comboBoxRoleMaster.SelectedItem != null;
            if (!valid_a) errorProviderUser.SetError(textBoxUserCode, "User Code can not be empty");
            if (!valid_b) errorProviderUser.SetError(textBoxUserName, "User Name can not be empty");
            if (!valid_c) errorProviderUser.SetError(textBoxPassword, "Password can not be empty");
            if (!valid_d) errorProviderUser.SetError(textBoxConfirmPassword, "Password is different");
            if (!valid_e) errorProviderUser.SetError(comboBoxTravelAgent, "Travel Agent can not be empty");
            // if (!valid_e) errorProviderUser.SetError(comboBoxRoleMaster, "Role can not be empty");
            return valid_a && valid_b && valid_c && valid_d && valid_e;
        }

        void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (isValidForm())
                {
                    m_user.UserCode = textBoxUserCode.Text;
                    m_user.UserName = textBoxUserName.Text;
                    m_user.Password = textBoxPassword.Text;
                    m_user.ActiveCode = checkBoxActive.Checked;
                    m_user.EmailID = textBoxEmail.Text;
                    m_user.ExpiryDate = dateTimePickerExpiry.Value;
                    m_user.PasswordExpired = checkBoxPasswordExpired.Checked;
                    //m_user.Role = (RoleMaster)comboBoxRoleMaster.SelectedItem;
                    m_user.CreatenBy = m_current_user.UserID;
                    m_user.ModificationBy = m_current_user.UserID;
                    m_user.TravelAgent = (TravelAgent)comboBoxTravelAgent.SelectedItem;
                    m_user.UserType = (UserType)Enum.Parse(typeof(UserType), comboBoxUserType.Text);
                    
                    m_user.PrinterNameBP = textBoxBPPrintername.Text;
                    m_user.PrinterNameWC = textBoxWCPrinterName.Text;
                    m_user.PrinterNameKIMS = textBoxKIMSPrinterName.Text;
                    m_user.DirectPrintBP = checkBoxBP.Checked;
                    m_user.DirectPrintWC = checkBoxWC.Checked;
                    m_user.DirectPrintKIMS = checkBoxKIMS.Checked;
                    m_user.MACAddress = textBoxMACAddress.Text.ToUpper();

                    updateUserRoleMasters();
                    m_user.ModificationTerminal = HttpContext.Current.User.Identity.Name.ToString() + "," + HttpContext.Current.Request.UserHostAddress;
                    if (m_user.UserID > 0)
                    {
                        m_userService.UpdateUser(m_user);
                    }
                    else
                    {
                        m_userService.InsertUser(m_user);
                    }
                    if (m_user.UserID == m_current_user.UserID)
                    {
                        m_mainForm.RefreshUserAndPermission(m_user);
                    }
                    m_parentForm.LoadAllUser();
                  //  MessageBox.Show("Record has been saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    MessageBox.Show("Record has been saved", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, new EventHandler(closeForm));
                    //clearForm();
                    //loadAllUser();
                    //setEditMode(EditMode.Saved);
                   // this.Close();
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error Exception", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

        }

        private void updateUserRoleMasters()
        {
            m_user.RoleMasters.Clear();
            foreach (DataGridViewRow v in dataGridViewRoleMasters.Rows)
            {
                if (dataGridViewRoleMasters[dataGridViewComboBoxColumnRoleMaster.Index, v.Index].Value == null) continue;
                string rolemasterName = dataGridViewRoleMasters[dataGridViewComboBoxColumnRoleMaster.Index, v.Index].Value.ToString();
                RoleMaster rolemaster = GetRoleMasterByName(rolemasterName);
                m_user.AddRoleMaster(rolemaster);
            }
        }

        void closeForm(object sender, EventArgs e)
        {
            this.Close();
        }

        private void setEditMode(EditMode editMode)
        {
            toolBarButtonSave.Enabled = (editMode == EditMode.Create || editMode == EditMode.Edit || editMode == EditMode.Saved || editMode == EditMode.Delete)&& m_current_user.RoleDetails(this.Name).NewFlag;
            toolBarButtonEdit.Enabled = (editMode == EditMode.Load) && m_current_user.RoleDetails(this.Name).UpdateFlag;
            m_editmode = editMode;
            labelEditMode.Text = "[" + editMode + "]";
        }

        private void enableForm(bool enable)
        {
            textBoxUserName.ReadOnly = !enable;
            textBoxUserCode.ReadOnly = !enable;
            textBoxPassword.ReadOnly = !enable;
            textBoxConfirmPassword.ReadOnly = !enable;
            checkBoxActive.Enabled = enable;
            textBoxEmail.ReadOnly = !enable;
            dateTimePickerExpiry.Enabled = enable;
            //comboBoxRoleMaster.Enabled = enable;
            checkBoxPasswordExpired.Enabled = enable;
            dataGridViewComboBoxColumnRoleMaster.ReadOnly = !enable;
            dataGridViewRoleMasters.AllowUserToAddRows = enable;
            dataGridViewButtonColumnRemove.Visible = enable;
            comboBoxTravelAgent.Enabled = enable && m_current_user.UserType == UserType.Administrators;
            comboBoxUserType.Enabled = enable && m_current_user.UserType == UserType.Administrators;

            checkBoxBP.Enabled = enable;
            checkBoxWC.Enabled = enable;
            textBoxMACAddress.ReadOnly = !enable;
            textBoxWCPrinterName.ReadOnly = !enable;
            textBoxBPPrintername.ReadOnly = !enable;
        }

        private void loadUser()
        {
            //m_user.Role = m_userService.GetRoleMasterByID(m_user.Role.RoleMasterID);
            m_user.TravelAgent = m_TravelAgentService.GetTravelAgentByID(m_user.TravelAgent.TravelAgentID);

            textBoxUserName.Text = m_user.UserName;
            textBoxUserCode.Text = m_user.UserCode;
            textBoxPassword.Text = m_user.Password;
            textBoxConfirmPassword.Text = m_user.Password;
            textBoxEmail.Text = m_user.EmailID;
            checkBoxActive.Checked = m_user.ActiveCode;
            dateTimePickerExpiry.Value = m_user.ExpiryDate;
            checkBoxPasswordExpired.Checked = m_user.PasswordExpired;
            comboBoxTravelAgent.Text = m_user.TravelAgent.ToString();
            //comboBoxRoleMaster.Text = m_user.Role.ToString();
            comboBoxUserType.Text = m_user.UserType.ToString();

            checkBoxBP.Checked = m_user.DirectPrintBP;
            checkBoxWC.Checked = m_user.DirectPrintWC;
            checkBoxKIMS.Checked = m_user.DirectPrintKIMS;
            textBoxMACAddress.Text = m_user.MACAddress;
            textBoxWCPrinterName.Text = m_user.PrinterNameBP;
            textBoxBPPrintername.Text = m_user.PrinterNameWC;
            textBoxKIMSPrinterName.Text = m_user.PrinterNameKIMS;

            dataGridViewRoleMasters.Rows.Clear();
            m_userService.GetUserRoleMasterByUserID(m_user);
            foreach (long key in m_user.RoleMasters.Keys)
            {
                RoleMaster m = m_user.RoleMasters[key];
                dataGridViewRoleMasters.Rows.Add(m.RoleName);
            }
        }

        private void comboBoxTravelAgent_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_editmode == EditMode.Create)
            {
                TravelAgent ta = (TravelAgent)comboBoxTravelAgent.SelectedValue;
                textBoxUserCode.Text = ta.Code;
                textBoxUserName.Text = ta.Code;
            }
        }

        private void checkBoxWC_CheckedChanged(object sender, EventArgs e)
        {
            textBoxWCPrinterName.Enabled = checkBoxWC.Checked;
        }

        private void checkBoxBP_CheckedChanged(object sender, EventArgs e)
        {
            textBoxBPPrintername.Enabled = checkBoxBP.Checked;
        }
    }
}